<template>
    <div>
        <div class="addBtn">
            <div style="display: flex;justify-content: space-around;margin-top: 30px;font-size: 14px;">
                    <div class="" style="display: flex;align-items: center">
                        <div>标题</div>
                        <div class="tabSearch" style="display: flex;">
                            <el-input style="margin: 0 10px ;" v-model="title" placeholder="请输入标题"
                                @input="titleChange"></el-input>
                        </div>
                    </div>



                </div>
            <el-button type="primary" @click="handleButtonAdd()">+ 添加</el-button>
            <el-dialog title="添加" :visible.sync="dialogTableVisible" :before-close="closeFormData">
                <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">

                    <el-form-item label="选择专家" prop="zhuanjia">
                        <el-button type="primary" @click="showExpertSelector = true">请选择</el-button>

                        <div class="zhuanjia-info" v-if="ruleForm.expert && ruleForm.expert.id">
                            <img :src="ruleForm.expert.avatar" alt="">
                            {{ ruleForm.expert.nickname }}
                        </div>
                    </el-form-item>
                    <el-form-item label="文章标题" prop="name">
                        <el-input v-model="ruleForm.title"></el-input>
                    </el-form-item>




                    <el-form-item label="封面" prop="cover">
                        <ImgCutter v-on:cutDown="cutDown" :cutWidth="400" :cutHeight="200">
                            <template #open>
                            </template>
                        </ImgCutter>
                        <el-image v-if="dialogImageUrl" style="width: 200px; height: 100px; margin-top: 10px"
                        :src="dialogImageUrl" fit="cover">
                    </el-image>
                    </el-form-item>




                    <el-form-item label="微信分享封面" prop="cover">
                        <ImgCutter v-on:cutDown="cutDown1" :cutWidth="500" :cutHeight="400">
                            <template #open>
                            </template>
                        </ImgCutter>
                        <el-image v-if="dialogImageUrl1" style="width: 500px; height: 400px; margin-top: 10px"
                        :src="dialogImageUrl1" fit="cover">
                    </el-image>
                    </el-form-item>

                    

                    <el-form-item label="分类">
                        <!-- <el-radio-group v-model="ruleForm.type" ref="radio">
                            <el-radio v-for="(item,index) in inforType" :key="index" :label="item.id">{{ item.text }}</el-radio>
                        </el-radio-group> -->
                        <el-checkbox-group v-model="ruleForm.type">




                            <el-checkbox v-for="(item, index) in inforType.slice(0, 3)" :key="index" :label="item.id">
                                {{ item.text }}
                            </el-checkbox>

                        </el-checkbox-group>

                        <!-- <el-radio-group v-model="ruleForm.type" >
                            <el-radio v-for="(item,index) in inforType" :key="index" :label="item.id">{{ item.text }}</el-radio>
                        </el-radio-group> -->
                    </el-form-item>
                    <el-form-item label="文章内容" prop="name">
                        <!-- <quill-editor ref="myQuillEditor" :options="quillOption" v-model="ruleForm.content">
                        </quill-editor> -->
                        <!--  -->
                        <div v-if="isVisible">
                            <WangEditor :content="contentData" @submit="workVadeUpdate" />
                        </div>
                    </el-form-item>
                    <el-form-item label="排序">
                        <el-input v-model="ruleForm.sort"></el-input>
                    </el-form-item>
                    <el-form-item label="显示">
                        <el-radio-group v-model="ruleForm.status">
                            <el-radio :label="1">显示</el-radio>
                            <el-radio :label="2">隐藏</el-radio>
                        </el-radio-group>
                    </el-form-item>

                </el-form>
                <div style="text-align: right;">
                    <el-button @click="clickDelete">取消</el-button>
                    <el-button type="primary" @click="clickConfirm">确认</el-button>
                </div>
            </el-dialog>
        </div>
        <el-table :data="tableData" style="width: 100%" :header-cell-style="{ 'text-align': 'center' }">
            <el-table-column prop="id" label="ID" align="center">
            </el-table-column>
            <el-table-column prop="title" label="标题" align="center">
            </el-table-column>
            <el-table-column prop="expert_name" label="专家" align="center">
            </el-table-column>
            <el-table-column prop="img_url" label="封面" align="center">
                <template slot-scope="scope">
                    <el-image style="width: 200px; height: 100px" :src="scope.row.img_url" fit="fill"></el-image>
                </template>
            </el-table-column>
            <el-table-column prop="img_url" label="微信分享封面" align="center">
                <template slot-scope="scope">
                    <el-image v-if="scope.row.share_cover" style="width: 250px; height: 200px" :src="scope.row.share_cover" fit="fill"></el-image>
                    <div v-else>
                        暂无
                    </div>
                </template>
            </el-table-column>
            <el-table-column prop="type_name" label="分类" align="center">
            </el-table-column>
            <el-table-column prop="create_time" label="创建时间" align="center">
            </el-table-column>
            <el-table-column prop="status" label="状态" align="center">
                <template slot-scope="scope">
                    <span v-if="scope.row.status == 1">
                        <div class="status-icon"></div>显示
                    </span>
                    <span v-if="scope.row.status == 2">
                        <div class="status-icon"></div>隐藏
                    </span>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center">
                <template slot-scope="scope">
                    <el-button size="small" type="primary" @click="handleButton1Click(scope.row, 1)">修改</el-button>
                    <el-button size="small" type="danger" @click="handleButton2Click(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <div class="tabListPage">
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                :current-page="currentPage" :page-sizes="pageSizes" :page-size="PageSize"
                layout="total, sizes, prev, pager, next, jumper" :total="totalCount">
            </el-pagination>
        </div>
        <ExpertSelector :visible.sync="showExpertSelector" @select="handleExpertSelect" />
    </div>

</template>

<script>
import { newsList, newsModify, getConfigList, newsDelete } from '../../../libs/api'
import quillConfig from '../../../libs/quill-config.js'
import WangEditor from '@/components/richText'
import ExpertSelector from '@/components/ExpertSelector.vue';
import ImgCutter from 'vue-img-cutter';
import axios from "axios";
import { title } from '@/settings';
export default {
    components: {
        WangEditor,
        ExpertSelector,
        ImgCutter
    },
    data() {
        return {
            rules: {
                // name: [
                //     { required: true, message: '请输入名称', trigger: 'blur' },
                // ],
            },
            quillOption: quillConfig,
            dialogImageUrl: '',
            dialogImageUrl1: '',
            dialogVisible: false,
            ruleForm: {
                type: [],
                expert: {}
            },
            tableData: [],
            dialogTableVisible: false,
            alltableData: [],
            currentPage: 1,
            totalCount: 1,
            PageSize: 5,
            pageSizes: [5, 10],
            content: '',
            inforType: [],
            contentData: '',
            type: 0,
            isVisible: false,
            types: [],
            showExpertSelector: false,
            title: '',
            

        }
    },
    created() {
        this.getNewsList()
        this.getConfigListData()
    },
    mounted() {
        // this.$refs.radio.$children.forEach((item) => {
        //     item.$refs.radio.removeAttribute("aria-hidden");
        // });
    },
    methods: {
        titleChange() {
            this.getNewsList()
        },
        async cutDown1(v) {
            const formData = new FormData();
            // 添加文件到表单数据
            formData.append('image', v.file);

            try {
                const response = await axios.post('https://api.zctj16888.com/admin/v1/image/ossUpload', formData, {
                    headers: {
                        'Content-Type': 'multipart/form-data'
                    }
                });
                // 上传成功后更新表单中的封面地址
                console.log(response)
                this.dialogImageUrl1 = response.data.data.url;
                this.$message.success('封面上传成功');
            } catch (error) {
                console.error('封面上传失败', error);
                this.$message.error('封面上传失败，请重试');
            }
        },
        async cutDown(v) {
            const formData = new FormData();
            // 添加文件到表单数据
            formData.append('image', v.file);

            try {
                const response = await axios.post('https://api.zctj16888.com/admin/v1/image/ossUpload', formData, {
                    headers: {
                        'Content-Type': 'multipart/form-data'
                    }
                });
                // 上传成功后更新表单中的封面地址
                console.log(response)
                this.dialogImageUrl = response.data.data.url;
                this.$message.success('封面上传成功');
            } catch (error) {
                console.error('封面上传失败', error);
                this.$message.error('封面上传失败，请重试');
            }
        },
        handleExpertSelect(v) {
            this.ruleForm.expert = v;

        },
        closeFormData() {
            Object.assign(this.ruleForm, {
                title: '',
                type: '',
                sort: '',
                status: ''
            });
            this.isVisible = false
            this.dialogTableVisible = false
            this.contentData = ''
        },
        workVadeUpdate(content) {
            this.ruleForm.content = content
        },
        getConfigListData() {
            getConfigList({

            }).then(res => {
                console.log(res)
                this.inforType = res.data.infoTypeList
            })
        },
        // 显示第几页
        handleCurrentChange(val) {
            // 改变默认的页数
            this.currentPage = val
            this.getNewsList()
        },
        // 分页
        // 每页显示的条数
        handleSizeChange(val) {
            // 改变每页显示的条数 
            this.PageSize = val
            // 点击每页显示的条数时，显示第一页
            console.log(val)
            this.PageSize = val
            // 改变每页显示的条数时，要将页码显示到第一页
            this.currentPage = 1
            this.getNewsList()
        },
        getNewsList() {
            newsList({
                page: this.currentPage,
                limit: this.PageSize,
                title: this.title
            }).then(res => {
                console.log('接口1', res)
                this.tableData = res.data.list
                this.totalCount = res.data.total
            })
        },
        deleteImg() {
            this.dialogImageUrl = ''
        },
        clickConfirm() {
            this.isVisible = false
            this.contentData = ''
            if (this.type == 0) {
                newsModify({
                    title: this.ruleForm.title,
                    img_url: this.dialogImageUrl,
                    status: this.ruleForm.status,
                    share_cover: this.dialogImageUrl1,
                    type: this.ruleForm.type.join(','),
                    content: this.ruleForm.content,
                    sort: this.ruleForm.sort,
                    expert_id: this.ruleForm.expert.id
                }).then(res => {
                    this.getNewsList()
                })
            } else {
                newsModify({
                    title: this.ruleForm.title,
                    // img_url:this.ruleForm.img_url,
                    share_cover: this.dialogImageUrl1,
                    img_url: this.dialogImageUrl,
                    status: this.ruleForm.status,
                    type: this.ruleForm.type.join(','),
                    content: this.ruleForm.content,
                    sort: this.ruleForm.sort,
                    id: this.ruleForm.id,
                    expert_id: this.ruleForm.expert.id
                }).then(res => {
                    this.getNewsList()
                })
            }
            this.dialogTableVisible = false
        },
        handleButton1Click(row, e) {

            if (!Array.isArray(row.type)) {
                row.type = [parseInt(row.type)]
            } else {
                row.type = row.type.map(item => parseInt(item))
            }
            this.isVisible = true
            this.type = e
            this.ruleForm = JSON.parse(JSON.stringify(row))
            this.dialogTableVisible = true
            this.contentData = row.content
            this.dialogImageUrl = this.ruleForm.img_url
            this.dialogImageUrl1 = this.ruleForm.share_cover
        },
        // 删除
        handleButton2Click(row) {
            this.$confirm('此操作将永久删除该资讯, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                newsDelete({
                    id: row.id
                }).then(res => {
                    this.getNewsList()
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        handleButtonAdd() {
            this.ruleForm.id = null
            this.ruleForm.type = []
            this.isVisible = true
            this.dialogTableVisible = true
        },
        clickDelete() {
            this.isVisible = false
            this.contentData = ''
            this.dialogTableVisible = false
        },
        handleRemove(file, fileList) {
            console.log(file, fileList);
        },
        handlePictureCardPreview(file) {
            this.dialogImageUrl = file.url;
            this.dialogVisible = true;
        },
        handleAvatarSuccess(res, file) {
            // this.imageUrl = URL.createObjectURL(file.raw);
            console.log(res.data.url)
            console.log(URL.createObjectURL(file.raw))
            this.ruleForm.img_url = res.data.url
            this.dialogImageUrl = res.data.url
            // this.ruleForm.img_url = URL.createObjectURL(file.raw)
        },
    }
}
</script>

<style>
.addBtn {
    margin-left: 30px;
    margin-bottom: 30px;
    margin-top: 30px;
}

.zhuanjia-info {
    display: flex;
    align-items: center;
    margin-top: 10px;
}

.zhuanjia-info>img {
    width: 50px;
    height: 50px;
    border-radius: 50%;
    margin-right: 10px;
}
</style>